import React, { useState, useImperativeHandle, useRef, useEffect } from "react"
import { Popup, NumberKeyboard, TextArea, Toast } from "antd-mobile"
import "./index.less"
import PopupDate from "../PopupDate"
import dayjs from "dayjs"
import { addBillApi, getListApi, updateBillApi } from "@/apis"
import IconFont from "../CustomIcon"
import { typeMap } from "@/utils"
import classNames from "classnames"

const PopupAddBill = ({ detail = {}, onReload }, ref) => {
  const id = detail && detail.id
  const [show, setShow] = useState(false) // 组件的显示和隐藏
  const [showK, setShowK] = useState(false) // 键盘的显示和隐藏
  const [payType, setPayType] = useState("expense") // 支出或收入类型
  const dateRef = useRef()
  const [date, setDate] = useState(new Date())
  const [amount, setAmount] = useState("")
  const [currentType, setCurrentType] = useState({}) // 当前选中账单类型
  const [expense, setExpense] = useState([]) // 支出类型数组
  const [income, setIncome] = useState([]) // 收入类型数组
  const [remark, setRemark] = useState("") //备注
  const [showRemark, setShowRemark] = useState(false) // 备注输入框展示控制

  useEffect(() => {
    if (id) {
      setPayType(detail.pay_type == 1 ? "expense" : "income")
      setCurrentType({
        id: detail.type_id,
        name: detail.type_name,
      })
      setRemark(detail.remark)
      setAmount(detail.amount)
      setDate(dayjs(Number(detail.date)).$d)
    }
  }, [detail])

  useEffect(() => {
    async function getList() {
      const { data } = await getListApi()
      const list = data.data.list
      const _expense = list.filter((i) => i.type == 1) // 支出类型
      const _income = list.filter((i) => i.type == 2) // 收入类型
      setExpense(_expense)
      setIncome(_income)

      if (!id) {
        setCurrentType(_expense[0])
      }
    }
    getList()
  }, [])

  const showKey = () => {
    setShowK(true)
  }
  const closeKey = () => {
    setShowK(false)
  }
  const showP = () => {
    setShow(true)
  }
  const closeP = () => {
    setShow(false)
  }
  useImperativeHandle(ref, () => {
    return {
      showP,
      closeP,
      showKey,
      closeKey,
    }
  })

  const selectDate = (val) => {
    setDate(val)
  }

  const handleMoney = (val) => {
    if (val === "." && amount.length === 0) return
    if (val === "." && amount.includes(".")) return
    if (
      val !== "." &&
      amount.includes(".") &&
      amount &&
      amount.split(".")[1].length >= 2
    )
      return
    setAmount(amount + val)
  }

  const handleDel = () => {
    let _amount = amount.slice(0, amount.length - 1)
    setAmount(_amount)
  }

  const handleConfirm = async () => {
    if (!amount) {
      Toast.show("请输入具体金额")
      return
    }
    const params = {
      amount: Number(amount).toFixed(2),
      type_id: currentType.id,
      type_name: currentType.name, // 账单种类名称
      date: dayjs(date).unix() * 1000, // 日期传时间戳
      pay_type: payType == "expense" ? 1 : 2, // 账单类型传 1 或 2
      remark: remark || "", // 备注
    }
    if (id) {
      params.id = id
      const response = await updateBillApi(params)
      Toast.show("修改成功")
    } else {
      const response = await addBillApi(params)
      // 重制数据
      setAmount("")
      setPayType("expense")
      setCurrentType(expense[0])
      setDate(new Date())
      setRemark("")
      Toast.show("添加成功")
    }
    setShow(false)
    setShowK(false)
    if (onReload) onReload()
  }

  const toggle3 = () => {
    dateRef.current && dateRef.current.showP()
    closeKey()
  }

  const dateVis = (val) => {
    if (val) {
      showKey()
    }
  }
  return (
    <div>
      <Popup
        visible={show}
        onMaskClick={() => {
          setShow(false)
          setShowK(false)
        }}
        onClose={() => {
          setShow(false)
          setShowK(false)
        }}
        ref={ref}
      >
        <div className="addWrap">
          <div className="filter">
            <div className="type">
              <span
                className={payType === "expense" ? "expense" : undefined}
                onClick={() => {
                  setPayType("expense")
                  setCurrentType(expense[0])
                }}
              >
                支出
              </span>
              <span
                className={payType === "income" ? "income" : undefined}
                onClick={() => {
                  setPayType("income")
                  setCurrentType(income[0])
                }}
              >
                收入
              </span>
            </div>
            <div className="time" onClick={() => toggle3()}>
              {dayjs(date).format("MM-DD")}
            </div>
          </div>
          <div className="money">
            <span className="sufix">¥</span>
            <span className="amount">{amount}</span>
          </div>
          {/* 账单类型 */}
          <div className="typeWrap">
            <div className="typeBody">
              {(payType === "expense" ? expense : income).map((item) => (
                <div
                  className="typeItem"
                  key={item.id}
                  onClick={() => setCurrentType(item)}
                >
                  <span
                    className={classNames({
                      iconfontWrap: true,
                      expenseactive:
                        payType === "expense" && currentType.id === item.id,
                      incomeactive:
                        payType === "income" && currentType.id === item.id,
                    })}
                  >
                    <IconFont type={typeMap[item.id].icon}></IconFont>
                  </span>
                  <span>{item.name}</span>
                </div>
              ))}
            </div>
          </div>
          {/* 备注 */}
          <div className="remark">
            {showRemark ? (
              <TextArea
                defaultValue={remark}
                showCount
                maxLength={50}
                placeholder="请输入备注信息"
                onChange={(val) => setRemark(val)}
                onBlur={() => setShowRemark(false)}
              />
            ) : (
              <span onClick={() => setShowRemark(true)}>
                {remark || "添加备注"}
              </span>
            )}
          </div>

          <div className="keyboard">
            <NumberKeyboard
              visible={showK}
              customKey={["-", "."]}
              confirmText="确定"
              showCloseButton={false}
              onInput={(val) => handleMoney(val)}
              onDelete={handleDel}
              onConfirm={handleConfirm}
            />
          </div>
        </div>
        <PopupDate
          ref={dateRef}
          onSelect={selectDate}
          mode="day"
          onVisable={dateVis}
        ></PopupDate>
      </Popup>
    </div>
  )
}

PopupAddBill.displayName = "MyPopupAddBill"

export default React.forwardRef(PopupAddBill)
